<template>
    <div class="chart-div" style="position:relative">
        <div style="position:absolute;right:10px;top:5px;z-index:1000">
            <exSwitch v-model="isShowGt" label="港通" size="mini" @change="onRefresh" v-if="isGt"></exSwitch>
            <el-button icon="el-icon-refresh" size="mini" type="text" @click="onRefresh" title="刷新"></el-button>
            <el-button icon="el-icon-search" size="mini" type="text" @click="showDialog" title="大图查看"></el-button>
        </div>
        
        
        <chartCom ref="curchart" :chrCfg="chrCfg" :size="size" @setChartOption="setChartOption"></chartCom>
        <chartDialog ref="chrWin" title="" :chrCfg="chrCfg"></chartDialog>
        
    </div>

</template>

<script>

import chartCom from "@/components/chart/chartCommon.vue";
import chartDialog from "@/components/chart/chartDialog.vue";

var upColor = '#ec0000';
var downColor = '#00da3c';

function splitData(rawData) {
    var categoryData = [];
    var values = [];
    var volumes = [];
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
    }

    return {
        categoryData: categoryData,
        values: values,
        volumes: volumes
    };
}

function calculateMA(dayCount, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
        }
        result.push(+(sum / dayCount).toFixed(3));
    }
    return result;
}

export default {
    components:{
        chartCom,
        chartDialog
    },
    props:["code","isGt","size"],
    data(){
        var that = this;
        return{
            curDate: this.$dayjs().format("MM-DD"),
            isShowGt: this.isGt==2?true:false,
            dataInfo:[],
            gtList: [],
            maxDataLen : 100,

            chrCfg:{
                // dataZoom : [ { type : 'inside'}],
                title:{
                    text:"K线图"
                },
                grid: [
                    {
                        left: '10%',
                        right: '8%',
                        height: '50%'
                    },
                    {
                        left: '10%',
                        right: '8%',
                        top: '73%',
                        height: '16%'
                    }
                ],
                backgroundColor: '#fff',
                animation: false,
                legend: {
                    bottom: 3,
                    left: 'center',
                    data: ['dataline', 'MA5', 'MA10', 'MA20', 'MA30','港通'],
                    selected: {dataline:true,MA5:false,MA10:false,MA20:false,MA30:false,"港通":true},
                    icon: 'circle',
                    itemHeight: 12, //修改icon图形大小
                    padding: 5,
                    itemGap: 10,
                    itemWidth : 5,
                    textStyle: {
                        fontSize: 12
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    backgroundColor: 'rgba(245, 245, 245, 0.8)',
                    borderWidth: 1,
                    borderColor: '#ccc',
                    padding: 10,
                    textStyle: {
                        color: '#000'
                    },
                    formatter: function (params) {
                        var arr = ['Date: ' + params[0].name + '<hr size=1 style="margin: 3px 0">'];

                        params.map(param=>{
                            if(param.seriesName=="dataline"){
                                arr = arr.concat([
                                    '开盘: ' + param.value[1] + '<br/>',
                                    '收盘: ' + param.value[2] + '<br/>',
                                    '最高: ' + param.value[3] + '<br/>',
                                    '最低: ' + param.value[4] + '<br/>',
                                    '振幅: ' + param.value[6] + '%<br/>',
                                    '涨跌幅: ' + param.value[7] + '%<br/>',
                                    '涨跌额: ' + param.value[8] + '<br/>',
                                    '换手: ' + param.value[9] + '%<br/>'
                                ])
                            }else if(param.seriesName=="港通"){
                                 arr.push('港通占比: ' + param.value[1] + '%<br/>');
                            }if(param.seriesName=="Volume"){
                                 arr.push('成交量: ' + param.value[1] + '<br/>');
                            }if(param.seriesName=="profit"){
                                 arr.push('盈亏: ' + param.value[1] + '<br/>');
                            }
                        })
                        arr.push('</hr>');
                        return arr.join('');
                    },
                    position: function (pos, params, el, elRect, size) {
                        var obj = {top: 10};
                        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                        return obj;
                    }
                    // extraCssText: 'width: 170px'
                },
                axisPointer: {
                    link: {xAxisIndex: 'all'},
                    label: {
                        backgroundColor: '#777'
                    }
                },
                // toolbox: {
                //     feature: {
                //         dataZoom: {
                //             yAxisIndex: false
                //         },
                //         brush: {
                //             type: ['lineX', 'clear']
                //         }
                //     }
                // },
                // brush: {
                //     xAxisIndex: 'all',
                //     brushLink: 'all',
                //     outOfBrush: {
                //         colorAlpha: 0.1
                //     }
                // },
                visualMap: [{
                    show: false,
                    seriesIndex: 5,
                    dimension: 2,
                    pieces: [{
                        value: 1,
                        color: downColor
                    }, {
                        value: -1,
                        color: upColor
                    }]
                }],
                xAxis: [
                    {
                        type: 'category',
                        data: [],
                        scale: true,
                        // boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax',
                        axisPointer: {
                            z: 100
                        }
                    },
                    {
                        type: 'category',
                        gridIndex: 1,
                        data: [],
                        scale: true,
                        // boundaryGap: false,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    },
                    {
                        type: 'category',
                        data: [],
                    }
                ],
                yAxis:[
                    {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    {
                        scale: true,
                        gridIndex: 1,
                        splitNumber: 2,
                        axisLabel: {show: false},
                        axisLine: {show: false},
                        axisTick: {show: false},
                        splitLine: {show: false}
                    },
                    {
                        name: '港通',
                        nameLocation: 'center',
                        type: 'value',
                        gridIndex: 0,
                        splitNumber: 2,
                        min: "dataMin",
                        axisLabel: {show: true},
                        axisLine: {show: true},
                        axisTick: {show: true},
                        splitLine: {show: false},
                        zlevel:9999,
                        z:9999
                    },
                ],
            },

            curchart : null,
            bigChart : null,
            isShowWin : false,
        }
    },
    computed:{
    },
    mounted(){
        this.curchart = this.$refs.curchart;
        this.onRefresh();
    },
    methods:{
        setChartOption(newoption){
            this.$emit("setChartOption",newoption)
        },
        onRefresh(){
            this.curchart.clearChartData();
            if(this.isShowGt){
                this.getGtList();
            }else{
                this.getLineData();
            }
        },
        getLineData(){
            if(!this.code) return;
            this.getStockLineInfo()
        },
        showDialog(){
            this.$refs.chrWin.showWin()
        },
        reDraw(){
            this.$nextTick(()=>{
                this.$refs.curchart.reDraw();
            });
        },
        setCharInfo(){
            var that = this;
            var data = splitData(this.dataInfo);
            this.chrCfg.series=[
                    {
                        name: 'dataline',
                        type: 'candlestick',
                        data: data.values,
                        itemStyle: {
                            color: upColor,
                            color0: downColor,
                            borderColor: null,
                            borderColor0: null
                        },
                    },
                    {
                        name: 'MA5',
                        type: 'line',
                        data: calculateMA(5, data),
                        smooth: false,
                        symbolSize: 0,
                        lineStyle: {
                            opacity: 0.5,
                            normal: {
                                lineStyle:{
                                    width:1//设置线条粗细
                                }
                            }
                        }
                    },
                    {
                        name: 'MA10',
                        type: 'line',
                        data: calculateMA(10, data),
                        smooth: false,
                        symbolSize: 0,
                        lineStyle: {
                            opacity: 0.5,
                            normal: {
                                lineStyle:{
                                    width:1//设置线条粗细
                                }
                            }
                        }
                    },
                    {
                        name: 'MA20',
                        type: 'line',
                        data: calculateMA(20, data),
                        smooth: false,
                        symbolSize: 0,
                        lineStyle: {
                            opacity: 0.5,
                            normal: {
                                lineStyle:{
                                    width:1//设置线条粗细
                                }
                            }
                        }
                    },
                    {
                        name: 'MA30',
                        type: 'line',
                        data: calculateMA(30, data),
                        smooth: false,
                        symbolSize: 0,
                        lineStyle: {
                            opacity: 0.5,
                            normal: {
                                lineStyle:{
                                    width:1//设置线条粗细
                                }
                            }
                        }
                    },
                    {
                        name: 'Volume',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: data.volumes
                    }
                ];
            // this.chrCfg.legend.data=[];
            // this.chrCfg.yAxis = [];
            this.chrCfg.xAxis[0].data = data.categoryData;
            this.chrCfg.xAxis[1].data = data.categoryData;


            if(this.isShowGt){
                var gtarr = [];
                this.gtList.map((item)=>{
                    gtarr.push([item.date,item.rate])
                })
                var seriescfg1={
                    name : "港通",
                    type : 'line',
                    data : gtarr,
                    // xAxisIndex: 0,
                    yAxisIndex: 2,
                    itemStyle: {
                        normal: {
                            // color: '#6cb041',
                            lineStyle:{
                                width:1//设置线条粗细
                            }
                        }
                    },
                    zlevel:9999,
                    z:9999
                }
                this.chrCfg.series.push(seriescfg1);
            }
            this.reDraw();
        },
        
        getStockLineInfo(){
            var code = this.code || "300869";
            var first = code.substring(0,1);
            if(code=="000001"){
                code= "1."+code;
            }else if(first=="0" || first=="3" || first=="1"){
                code = "0."+code;
            }else {
                code = "1."+code;
            }
            this.$axios.get(`http://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${code}&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&ut=7eea3edcaed734bea9cbfc24409ed989&klt=101&fqt=1&beg=0&end=20500000`)
            .then((res) => {
                if (res.data.data) {
                    this.dataInfo=[];
                    var data = res.data.data;
                    this.name = data.name;
                    this.chrCfg.title.text = this.name+"("+this.code+")" ;
                    var len = data.klines.length;
                    if(len>110){
                        data.klines = data.klines.splice(len-100,100)
                    }
                    data.klines.map((item,idx)=>{
                        if(idx==this.maxDataLen) return;
                        var arr = item.split(",");
                        var row = [];
                        row.push(arr[0]);//日期
                        row.push(arr[1]*1);//开
                        row.push(arr[2]*1);//收
                        row.push(arr[3]*1);//高
                        row.push(arr[4]*1);//低
                        row.push(arr[6]*1);//金额
                        row.push(arr[7]*1);//振幅
                        row.push(arr[8]*1);//涨跌幅
                        row.push(arr[9]*1);//涨跌额
                        row.push(arr[10]*1);//换手

                        this.dataInfo.push(row);
                    })
                    this.setCharInfo();

                    //[["2004-01-02",10452.74,10409.85,10367.41,10554.96,168890000]]
                } else {
                    this.$message.error(res.data.message);
                }
            })
        },
        getGtList(){
            var code = this.code;
            var first = code.substring(0,1);
            if(first=="0" || first=="3" || first=="1"){
                code = "sz"+code;
            }else {
                code = "sh"+code;
            }
            this.gtList = [];
            this.$axios.get(`https://www.uldata.com/hsgt/${code}`).then((res) => {
                if(res.data){
                    this.gtList = this.getGtArray(res.data);
                    if(this.gtList.length==0){
                        this.$message.info(this.code+" 未查询到港股通交易数据");
                    }
                    this.getLineData();
                }else{
                    this.$message.error(JSON.stringify(res.data));
                }
            })
        },
        getGtArray(html){
            var list = [];
            var key_str = "";
            var val_str = "";
            var json_str = "";
            var key_pos = html.indexOf("__NUXT__");
            if(key_pos==-1) return list;
            var key_start = key_pos+19;
            var key_end = html.indexOf(")",key_start);
            key_str = html.substring(key_start,key_end);
            if(key_str.length<40) return list;
            

            var val_pos = html.indexOf("serverRendered");
            if(val_pos==-1) return list;
            var val_start = val_pos+22;
            var val_end = html.indexOf(")",val_start);
            val_str = html.substring(val_start,val_end);
            val_str = val_str.replace(/\"([0-9]+,)+[0-9]+\"/g,"replace"); //替换掉 ,"479,390,295",  这种数据,不然会导致顺序对应失败
    //        System.out.println(val_str);

            var json_pos = html.indexOf("ggtTableData");
            if(json_pos==-1) return list;
            var json_start = json_pos+13;
            var json_end = html.indexOf("]",json_start)+1;
            json_str = html.substring(json_start,json_end);
    //        System.out.println(json_str);

            var keyarr = key_str.split(",");
            var valarr = val_str.split(",");
            var valmap = {};
            for(var i=0;i<keyarr.length;i++){
                if(i==valarr.length) break;
                var val = valarr[i];
                val = val.replaceAll("\"","");
                valmap[keyarr[i]]=val;
            }

            json_str = json_str.replace(/:([a-zA-Z0-9$_]+)([,|\}])/g,":\"$1\"$2");
            // console.info(json_str)
            var arr = eval(json_str);
            var len = arr.length;
            var start = len - this.maxDataLen;
            if(start<0) start = 0;
            arr.reverse();
            for(var i=start;i<arr.length;i++){
                var item = arr[i];
                var db = {};
                db.date = valmap[item.cgdate];
                db.code = valmap[item.ano_j];
                db.name = valmap[item.aname];
                if(isNaN(item.cgper)){
                    db.rate = valmap[item.cgper];
                }else{
                    db.rate = item.cgper;
                }
                db.price = valmap[item.endprice];
                list.push(db);
            }
            console.log(list);
            return list;
        }
    }
}
</script>

<style lang="less" scope>

.chart-div{
    border:1px lightgray solid;
    display: inline-block;
    margin-bottom: 5px;
}


</style>